package mashuaiproject.mashuaiproject.controller;

import mashuaiproject.mashuaiproject.dto.FileDtos;
import mashuaiproject.mashuaiproject.mapper.UserMapper;
import mashuaiproject.mashuaiproject.model.Users;
import mashuaiproject.mashuaiproject.provider.UcloudProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Controller
public class FileController {
    @Autowired
    private UcloudProvider ucloudProvider;
    @Autowired
    private UserMapper userMapper;
    @ResponseBody
    @RequestMapping("/file/{action}")
    public FileDtos upload(HttpServletRequest request,@PathVariable(name = "action") String action){
        System.out.println("action:"+action);
        if (action.equals("upload")){
            try {
                MultipartHttpServletRequest multipartHttpServletRequest=(MultipartHttpServletRequest) request;
                MultipartFile file = multipartHttpServletRequest.getFile("editormd-image-file");
                String filename= ucloudProvider.uploads(file.getInputStream(), file.getContentType(), file.getOriginalFilename());
                FileDtos fileDtos = new FileDtos();
                fileDtos.setMessage("成功");
                fileDtos.setUrl(filename);
                fileDtos.setSuccess(1);
                return fileDtos;

            }catch (IOException e){
                e.printStackTrace();
            }

        }
        //上传头像。执行插入操作
        if(action.equals("head")){
            try {
                MultipartHttpServletRequest multipartHttpServletRequest=(MultipartHttpServletRequest) request;
                MultipartFile file = multipartHttpServletRequest.getFile("editormd-image-file");
                String filename= ucloudProvider.uploads(file.getInputStream(), file.getContentType(), file.getOriginalFilename());
                FileDtos fileDtos = new FileDtos();
                fileDtos.setMessage("成功");
                fileDtos.setUrl(filename);
                fileDtos.setSuccess(1);
                //插入图片；
                Users users= (Users) request.getSession().getAttribute("user");
                int id=users.getId();
                System.err.println("用户id:"+id+"-图片："+filename);

                userMapper.updateAvatarul(id,filename);

                return fileDtos;

            }catch (IOException e){
                e.printStackTrace();
            }

        }


        return  null;
    }
}
